package com.atguigu.controller;

import com.atguigu.common.MyBaseContext;
import com.atguigu.common.R;
import com.atguigu.entity.Employee;
import com.atguigu.service.impl.EmployeeServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

import static com.atguigu.common.R.success;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeServiceImpl employeeService;

    //登录页面
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.将页面提交的密码进行MD5加密处理，
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee employee1 = employeeService.getOne(queryWrapper);

        //3.如果没有查询到结果，则返回登录失败提示
        if (employee1 == null) {
            return R.error("登陆失败");
        }

        //4.密码比对，如果不一致，登录失败
        if (!password.equals(employee1.getPassword())) {
            return R.error("登陆失败");
        }

        //5.查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (employee1.getStatus() == 0) {
            return R.error("员工已禁用");
        }

        //6.登陆成功，将员工id存入session中并返回结果
        HttpSession session = request.getSession();
        session.setAttribute("employee_id", employee1.getId());
        //7.将employee_id放入当前线程
        return success(employee1);
    }

    //退出登录
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        //清理session中保存的用户信息
        session.removeAttribute("employee_id");
        return success("退出登录");
    }

    //添加员工信息
    @PostMapping
    public R<String> addEmployee(@RequestBody Employee employee, HttpServletRequest request) {
        log.info(employee.toString());
        //设置初始密码(使用MD5加密），记录创建时间和最后更新时间，创建者
//        LocalDateTime createTime = LocalDateTime.now();
//        employee.setCreateTime(createTime);//创建时间
        //自定义密码123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //最后更新时间
//        employee.setUpdateTime(createTime);
        //创建者
        //先获取当前员工登录的Id
        //Long employeeId = (Long) request.getSession().getAttribute("employee_id");
//        employee.setCreateUser(employeeId);
        //最后的更新者
//        employee.setUpdateUser(employeeId);

        //将从客户端页面获取到的员工对象存储到数据库中
        employeeService.save(employee);

        return success("添加员工成功");
    }

    //获取员工信息并分页
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={},pagesize={},name={}", page, pageSize, name);
        //创建一个分页对象实例
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        //根据name从数据库中查询相关的员工信息
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(name), Employee::getName, name);

        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        return success(pageInfo);
    }

    //更新员工数据
    @PutMapping
    public R<String> updata(@RequestBody Employee employee, HttpServletRequest request) {
        log.info(employee.toString());

        //将获取到的信息传入数据库中
        long employee_id = (long) request.getSession().getAttribute("employee_id");

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(employee_id);
        employee.setId(employee_id);
        employeeService.updateById(employee);

        return R.success("员工信息更新成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable("id") Long id){
        log.info(id.toString());
        Employee employee = employeeService.getById(id);
        if(employee==null){
            return R.error("没有查询到相关员工信息");
        }
        return R.success(employee);
    }

}
